package router

import (
	"fmt"
	"gitee.com/git_public/vfaith/fount/frame"
	"gitee.com/git_public/vfaith/fount/middleware"
	"net/http"
	"strings"
)

type AppRouter struct {
	contextName string //上下文名称
	appName     string //应用名称
	appPath     string //包入口路径
	appProtocol int    //协议类型：1-api, 2-web
	tokenName   string //令牌名称
	*http.ServeMux
}

func NewAppRouter(contextName string, appName string, appProtocol int, tokenName string) *AppRouter {
	router := &AppRouter{
		contextName: contextName,
		appName:     appName,
		appPath:     fmt.Sprintf("expose/%s/", appName),
		appProtocol: appProtocol,
		tokenName:   tokenName,
		ServeMux:    http.NewServeMux(),
	}

	// 为Application注册路由
	frame.RouterRegistry(router)

	// 设置自定义路由器
	http.Handle(fmt.Sprintf("/%s/%s/", contextName, appName), router)

	return router
}

func (cm *AppRouter) AppName() string {
	return fmt.Sprintf("%s|||%d", cm.appName, cm.appProtocol)
}

func (cm *AppRouter) AppPath() string {
	return cm.appPath
}

func (cm *AppRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 获取请求的路径
	path := r.URL.Path

	if strings.Index(path, "/login") > 0 || middleware.Auth(w, r, cm.tokenName, "") {
		// 处理其他路径
		cm.ServeMux.ServeHTTP(w, r)
	}
}
